package jmind.core.redis;

import com.alibaba.fastjson.JSON;
import jmind.base.lang.IProperties;
import jmind.base.util.DataUtil;
import redis.clients.jedis.JedisCluster;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:  redis json 序列化
 *
 * @author weibo.xie
 * @date : create in 5:14 下午 2021/5/17
 */
public class RedisJsonCluster extends RedisCluster {
    public RedisJsonCluster(JedisCluster jedisCluster) {
        super(jedisCluster,null);
    }

    public RedisJsonCluster(String name, IProperties p) {
        super(name, p);
    }

    public boolean setObject(String key, Object o) {
        if(o==null || key==null ){
            return false;
        }
        String value= o instanceof String? (String)o: JSON.toJSONString(o);
        String setObjectRet = set(key, value);
        return "OK".equalsIgnoreCase(setObjectRet);

    }

    public boolean setObject(String key,int seconds, Object o) {
        if(o==null || key==null){
            return false;
        }
        String value= o instanceof String? (String)o:JSON.toJSONString(o);
        String setObjectRet = setex(key,seconds,value);
        return "OK".equalsIgnoreCase(setObjectRet);
    }

    public <T> T getObject(String key, Class<T> clazz) {
        String string = get(key);
        if (DataUtil.isEmpty(string))
            return null;
        if(String.class.equals(clazz)){
            return (T) string;
        }
        return JSON.parseObject(string, clazz);
    }

    @Override
    public Map<String, Object> getObjects(Collection<String> keys, Class clazz) {
        int index=0;
        Map<String, Object> map= new HashMap<>();
        List<String> mget = jc.mget(keys.toArray(new String[0]));
        for(String key:keys){
            try {
                String objectStr = mget.get(index++);
                if(objectStr!=null){
                    Object object = JSON.parseObject(objectStr,clazz);
                    map.put(key,object);
                }
            } catch (Exception e) {
                logger.error("",e);
            }
        }
        return map;
    }

    public <T> List<T> getArray(String key, Class<T> clazz){
        String s=get(key);
        return JSON.parseArray(s,clazz);
    }
}